// 记录用户的操作信息
import type { RouteLocationNormalizedGeneric } from "vue-router";

interface TabItem {
  path: string;
  label: string;
  componentName: string;
  cache: boolean;
}

// interface OperateState {
//   tabs: TabItem[];
//   tabRecords: string[];
// }

export const useOperateStore = defineStore(
  "operate",
  () => {
    const tabs = ref<TabItem[]>([]);
    const tabRecords = ref<string[]>([]);

    // 返回true 新增一个 false: 非新增
    function addRecords(path: string): boolean {
      let index = tabRecords.value.indexOf(path);
      if (-1 === index) {
        tabRecords.value.push(path);
        return true;
      } else {
        tabRecords.value.splice(index, 1);
        tabRecords.value.push(path);
        return false;
      }
    }

    function deleteRecords(path: string) {
      let index = tabRecords.value.indexOf(path);
      if (-1 !== index) tabRecords.value.splice(index, 1);
      else console.error("delete records code error");
    }
    function deleteTabs(path: string) {
      let index = tabs.value.findIndex((i) => path === i.path);
      if (-1 !== index) tabs.value.splice(index, 1);
      else console.error("delete tab code error");
    }

    function clickMenu(to: RouteLocationNormalizedGeneric) {
      let path = to.path;
      let isNew = addRecords(path);
      let componentName = to.meta.componentName;
      let cache = to.meta.cache ?? true;
      if (isNew && componentName) {
        let label = to.meta.label;
        tabs.value.push({
          path,
          label,
          componentName,
          cache,
        });
      }
    }

    function closeTab(path: string) {
      deleteRecords(path);
      deleteTabs(path);
    }
    return { tabs, tabRecords, clickMenu, closeTab };
  },
  {
    persist: {
      key: "operation-record",
      storage: sessionStorage,
    },
  }
);
